﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ZGRemote.Server.UI.ViewModels;

namespace ZGRemote.Server.UI.Views
{
    /// <summary>
    /// RemoteShell.xaml 的交互逻辑
    /// </summary>
    public partial class RemoteShell : UserControl
    {
        private RemoteShellViewModel viewModel = default!;
        public RemoteShell()
        {
            InitializeComponent();
            
            DataContextChanged += DataContextChanged_;
  
        }

        private void DataContextChanged_(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue is RemoteShellViewModel vm)
            {
                viewModel = vm;
                foreach (var i in viewModel.Docs)
                {
                    ConsoleBox.Inlines.Add(i);
                }

                this.Dispatcher.BeginInvoke(() =>
                {
                    RichTextBox_.ScrollToEnd();
                });

                vm.Docs.CollectionChanged += Docs_CollectionChanged;
            }
        }

        private void Docs_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                foreach (var item in e.NewItems!)
                {
                    ConsoleBox.Inlines.Add((Run)item);
                    RichTextBox_.ScrollToEnd();
                }
            }
        }

        private void CommandBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                viewModel.DoCommandCommand.Execute(null);
            }
        }
    }
}
